package com.tdam2011.grupo05.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.tdam2011.grupo05.R;

public class ConectividadReciver extends BroadcastReceiver {

	private boolean noConectado;
	private static String messaje = "";

	private static final int CONNECTION = 1;
	private NetworkInfo netInfo;

	@Override
	public void onReceive(Context context, Intent intent) {

		String accion = intent.getAction();
		if (accion.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

			noConectado = intent.getBooleanExtra(
					ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

			netInfo = (NetworkInfo) intent
					.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

			if (netInfo.getTypeName().equalsIgnoreCase("mobile")) {
				if (noConectado) {

					notifyMobileConnection(context);
				} else {
					notifyDisconnection(context);

				}

			} else {
				if (netInfo.getTypeName().equalsIgnoreCase("wifi")) {

					if (noConectado) {
						notifyWiFiConnection(context);
					} else {
						notifyDisconnection(context);
					}
				}
			}

		}

	}

	public static void notifyDisconnection(Context context) {
		messaje = context.getString(R.string.noConnectivity);

		Notification notification = loadNotification(context);

		getManager(context).notify(CONNECTION, notification);
	}

	public static void notifyMobileConnection(Context context) {
		messaje = context.getString(R.string.g3Connectivity);

		Notification notification = loadNotification(context);

		getManager(context).notify(CONNECTION, notification);
	}

	public static void notifyWiFiConnection(Context context) {
		messaje = context.getString(R.string.wiFiConnectivity);

		Notification notification = loadNotification(context);

		getManager(context).notify(CONNECTION, notification);
	}

	private static Notification loadNotification(Context context) {

		Notification notification = null;

		Intent notificationIntent = new Intent();

		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);

		notification = new Notification(R.drawable.ic_action_config,
				"Conectividad", System.currentTimeMillis());

		notification.setLatestEventInfo(context,
				context.getString(R.string.information_lavel), messaje,
				contentIntent);

		return notification;

	}

	private static NotificationManager getManager(Context context) {
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		return mNotificationManager;
	}

}
